﻿using Comm.Model;
using Comm.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace Comm.Web.Action
{
    /// <summary>
    /// BookManager 的摘要说明
    /// </summary>
    public class BookManager : BaseHander
    {
        BLL.CategoriesService bllCate = new BLL.CategoriesService();
        BLL.BooksService bllbooks = new BLL.BooksService();
        BLL.PublishersService bllpulish = new BLL.PublishersService();
        public override void SonLoad()
        {
            string type =context.Request.Params["type"];
            string[] types = type.Split(',');
            if (types.Length > 1)
            {
                type = types[1];
            }
            else 
            {
                type = types[0];
            }
            switch (type) 
            {
                case "get":
                    doEditPanel();
                    break;
                case "m":
                    doUpdate();
                    break;
                case "add":
                    doAdd();
                    break;
                case "d":
                    doDel();
                    break;
                case "editSon":
                    doEditSonPanel();
                    break;
                case "ds":
                    doUpdateSonMenu();
                    break;
                case "delson":
                    doDelSonMenu();
                    break;
                case "addson":
                    doSonAdd();
                    break;
                case "dobookPanel":
                    doBookPanel();
                    break;
                case "upimg":
                    doUpimg();
                    break;
                case "doBookEdit":
                    doBookEdit();
                    break;
                case "doBookAdd":
                    doBookAdd();
                    break;
                case "delbook":
                    doDelBook();
                    break;
            }
        }

        public void doEditPanel() 
        {
            int id = int.Parse(Request.QueryString["Cid"]);
            try
            {
                IList<Model.Categories> list = bllCate.QuerySingle1(id);
                AjaxMsgHelper.AjaxMsg("ok", "加载成功~", Utility.JsonHelper.Serialize(list));
            }
            catch(Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }
        public void doEditSonPanel()
        {
            int id = int.Parse(Request.QueryString["Sid"]);
            try
            {
                Model.Categories model = bllCate.QuerySingle(id);
                AjaxMsgHelper.AjaxMsg("ok", "加载成功~", Utility.JsonHelper.Serialize(model));
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }
        public void doDel()
        {
            int id = int.Parse(Request.Form["tid"]);
            try
            {
                bllCate.Delete(id);
                AjaxMsgHelper.AjaxMsg("ok", "删除成功~");
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }

        public void doDelSonMenu()
        {
            int id = int.Parse(Request.Form["sonId"]);
            try
            {
                bllCate.Delete(id);
                AjaxMsgHelper.AjaxMsg("ok", "删除成功~");
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }

        public void doUpdate()
        {
            Model.Categories model = new Model.Categories()
            { 
               Id =int.Parse(Request.Form["MgrId"]),
               Name = Request.Form["MgrName"],
               Pid =int.Parse(Request.Form["MgrPid"])
            };
            try
            {
                bllCate.Update(model);
                string strJson =JsonHelper.Serialize(model);
                AjaxMsgHelper.AjaxMsg("ok", "更新成功~", strJson);
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }

        public void doUpdateSonMenu()
        {
            Model.Categories model = new Model.Categories()
            {
                Id = int.Parse(Request.Form["MgrSonId"]),
                Name = Request.Form["BookType"],
                Pid = int.Parse(Request.Form["MgPid"])
            };
            try
            {
                bllCate.Update(model);
                DataTable dt = bllCate.GetSonMenu(int.Parse(Request.Form["MgPid"]));
                string strJson = JsonHelper.Serialize(dt);
                AjaxMsgHelper.AjaxMsg("ok", "更新成功~", strJson);
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }
        public void doAdd()
        {
            Model.Categories model = new Model.Categories()
            {
                Name = Request.Form["MgrName"],
                Pid = int.Parse(Request.Form["MgrPid"])
            };
            try
            {
                bllCate.Insert(model);
                DataTable dt = bllCate.getMaxId();
              Model.Categories model1=bllCate.QuerySingle(int.Parse(dt.Rows[0]["Id"].ToString()));
              string strJson = JsonHelper.Serialize(model1);
                AjaxMsgHelper.AjaxMsg("ok", "新增成功~", strJson);
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }
        public void doSonAdd()
        {
            Model.Categories model = new Model.Categories()
            {
                Name = Request.Form["BookType"],
                Pid = int.Parse(Request.Form["TypeName"])
            };
            try
            {
                bllCate.Insert(model);
                DataTable dt = bllCate.getMaxId();
                Model.Categories model1 = bllCate.QuerySingle(int.Parse(dt.Rows[0]["Id"].ToString()));
                string strJson = JsonHelper.Serialize(model1);
                AjaxMsgHelper.AjaxMsg("ok", "新增成功~", strJson);
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }

        public void doBookPanel() 
        {
            int bookid=int.Parse(Request.Form["bookId"]);
            Books book = bllbooks.QuerySingle(bookid);
            IList<Categories> list1 = bllCate.GetAllCategories();
            IList<Publishers> list2 = bllpulish.GetPublishersList();
            Comm.Model.commom.GetBookList<Books> getBookData = new commom.GetBookList<Books> ()
            {
                GetboksList = book,
               GetPublishList=list2,
               GetCategoryList=list1
            };
            AjaxMsgHelper.AjaxMsg("ok", "数据加载成功！~~", JsonHelper.Serialize(getBookData));
        }

        public void doUpimg() 
        {
            //1.接收图片
            //验证，如果没有上传文件，则返回
            if (Request.Files.Count <= 0)
            {
                PageHelper.WriteJsMsg("参数错误~！", "../View/BookManager.aspx?bookTypelist=2");
                Response.End();
            }
            //1.1获取上传上来的 文件
            HttpPostedFile uploadFile = Request.Files[0];
            if (!uploadFile.ContentType.Contains("image/"))
            {
                PageHelper.WriteJsMsg("只能上传图片~！", "../View/BookManager.aspx?bookTypelist=2");
                Response.End();
            }
            //1.2验证图片大小
            if (uploadFile.ContentLength <= 2 || uploadFile.ContentLength > 4 * 1024 * 1024)
            {
                PageHelper.WriteJsMsg("图片太小或太大（4M以内）~！", "../View/BookManager.aspx?bookTypelist=2");
                Response.End();
            }
            //1.2 生成 新的图片名
            string strNewImgName = FileHelper.NewFileName(uploadFile.FileName);
            //1.3 生成 缩略图变名
            string PathName =Request.Form["ISBN"]+ Path.GetExtension(uploadFile.FileName);
            string strNewThumbName = PathName;

            //2.保存图片 和 生成缩略图
            FileHelper.SaveImgAndThumb(uploadFile, strNewThumbName, "/images/BookCovers/", 150, 188);
            Response.Write("<script>alert('上传成功')</script>");
            //Response.Write("<script>window.parent.Finish();</script>");
        }
        public void doBookEdit()
        {
            Model.Books model = new Model.Books()
            {
                Id = int.Parse(Request.Form["BookId"]),
                Author = Request.Form["Author"],
                Title = Request.Form["BookName"],
                PublisherId = int.Parse(Request.Form["PublishId"]),
                PublishDate = DateTime.Parse(Request.Form["PublishDate"]),
                ISBN = Request.Form["ISBN"],
                UnitPrice = int.Parse(Request.Form["UnitPrice"]),
                ContentDescription = Request.Form["CommentDes"],
                AurhorDescription = Request.Form["AuthorDes"],
                CategoryId = int.Parse(Request.Form["TypeBookName"])
            };
            try
            {
                bllbooks.Update(model);
                Books book = bllbooks.QuerySingle(int.Parse(Request.Form["BookId"]));
               IList<Categories> list1 = bllCate.GetAllCategories();
               IList<Publishers> list2 = bllpulish.GetPublishersList();
               Comm.Model.commom.GetBookList<Books> getBookData = new commom.GetBookList<Books>()
               {
                   GetboksList = book,
                   GetPublishList = list2,
                   GetCategoryList = list1
               };
               AjaxMsgHelper.AjaxMsg("ok", "修改成功~", JsonHelper.Serialize(getBookData));
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }
        public void doBookAdd()
        {
            Model.Books model = new Model.Books()
            {
                Author = Request.Form["Author"],
                Title = Request.Form["BookName"],
                PublisherId = int.Parse(Request.Form["PublishId"]),
                PublishDate = DateTime.Parse(Request.Form["PublishDate"]),
                ISBN = Request.Form["ISBN"],
                UnitPrice = int.Parse(Request.Form["UnitPrice"]),
                ContentDescription = Request.Form["CommentDes"],
                AurhorDescription = Request.Form["AuthorDes"],
                CategoryId = int.Parse(Request.Form["TypeBookName"])
            };
            try
            {
                int maxId =bllbooks.Insert(model);
                Books book = bllbooks.QuerySingle(maxId);
                IList<Categories> list1 = bllCate.GetAllCategories();
                IList<Publishers> list2 = bllpulish.GetPublishersList();
                Comm.Model.commom.GetBookList<Books> getBookData = new commom.GetBookList<Books>()
                {
                    GetboksList = book,
                    GetPublishList = list2,
                    GetCategoryList = list1
                };
                AjaxMsgHelper.AjaxMsg("ok", "添加成功~", JsonHelper.Serialize(getBookData));
            }
            catch (Exception ex)
            {
                AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
            }
        }
        public void doDelBook() 
        {
            bllbooks.Delete(int.Parse(Request.Form["bookid"]));
            AjaxMsgHelper.AjaxMsg("ok","删除成功！~~");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}